#include <string>
#include <stdio.h>
#include <stdlib.h>

#include "H264DecoderFrame.h"
#include "H264FileParser.h"
#include "CoderToJpg.h"

extern int Parser_Test();
extern int Coder_Test();

int main(int argc, char* argv[])
{
	//Parser_Test();
	////Coder_Test();
	//return 0;
	if (argc < 2)
	{
		printf("need file name\n");
		return -1;
	}

	H264FileParser objH264FileParser;
	//F:\ThirdProtocol\code_thirdprotocol\nuuo\mediastreamgateway\NuppTest\video\HARRY_FHD_8Mb_30FPS2.h264
	string strFileName(argv[1]); //"..\\testvideo\\test.h264";
	int nRet = -1;
	nRet = objH264FileParser.open(strFileName);
	if (nRet != 0)
	{
		printf("H264FileParser open err %d\n", nRet);
		return -1;
	}

	H264DecoderFrame objH264DecoderFrame;
	nRet = objH264DecoderFrame.init();
	if (nRet != 0)
	{
		printf("H264DecoderFrame init err %d\n", nRet);
		return -1;
	}

	nRet = objH264DecoderFrame.open(strFileName);
	if (nRet != 0)
	{
		printf("H264DecoderFrame open err %d\n", nRet);
		return -1;
	}

	CoderToJpg objCoderToJpg;
	objCoderToJpg.init();

	int nCnt = 0;
	AVPacket* pobjAVPacket = NULL;
	AVFrame* pobjAVFrame = NULL;
	while(true)
	{
		nRet = objH264FileParser.getAVPacket(pobjAVPacket);
		printf("getAVPacket %d\n", nRet);
		if (nRet < 0)
		{
			printf("H264FileParser.getNalu err %d\n", nRet);
			break;
		}
		char* szData = (char*)pobjAVPacket->data;
		int nLen = pobjAVPacket->size;

		nRet = objH264DecoderFrame.deCoderOneFrame(szData, nLen, pobjAVFrame);
		if (nRet < 0)
		{
			printf("H264DecoderFrame deCoderOneFrame err %d\n", nRet);
			continue;
		}
		char p[128] = {0};
		memset(p, 0, 128);
		sprintf(p, ".//test_%d.jpg", nCnt++);
		printf("------pic file %s\n", p);
		string strFileName(p);

		objCoderToJpg.setWidth(pobjAVFrame->width);
		objCoderToJpg.setHeight(pobjAVFrame->height);

		AVFrame objYUVFrame;
		memset(&objYUVFrame, 0, sizeof(AVFrame));

		objYUVFrame.data[0] = pobjAVFrame->data[0];
		objYUVFrame.linesize[0] = pobjAVFrame->linesize[0];

		objYUVFrame.data[1] = pobjAVFrame->data[1];
		objYUVFrame.linesize[1] = pobjAVFrame->linesize[1];

		objYUVFrame.data[2] = pobjAVFrame->data[2];
		objYUVFrame.linesize[2] = pobjAVFrame->linesize[2];
		objYUVFrame.pts = nCnt;

		nRet = objCoderToJpg.coderFrameToPic(&objYUVFrame, strFileName);
		if (nRet != 0)
		{
			printf("CoderToJpg coderFrameToPic err %d\n", nRet);
			continue;
		}
	}

	objH264DecoderFrame.close();
	objCoderToJpg.close();
	objH264FileParser.close();
	return 0;
}
